// pages/serviceintro/serviceintro.js
import { ajax, src, util } from "../../utils/util.js";
// import { App } from "../../app.js";
// let isIphoneX = App.globalData.isIphoneX;


const app = getApp()
let isIphoneX = app.globalData.isIphoneX;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isPhoneAuth:false, //手机号授权遮罩提示
    uqid:'',
    phone:'',//手输的
    // tel:'',//授权电话
    goods_id:'',
    isplan:false,
    session_key: '',
    hfinfo:[],
    islogin:false ,
    isIphoneX: isIphoneX
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    var goods_id = options.goods_id;
    var uqid = wx.getStorageSync("uqid");
    this.setData({
      goods_id: goods_id,
      uqid: uqid
    });
    if(uqid != undefined && uqid != ''){
      this.isPatient(); //判断是否有进展
    }
    this.getHfInfo(uqid, goods_id);

    var that = this;
    // 查看是否授权
    // wx.getSetting({
    //   success(res) {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称
    //       wx.getUserInfo({
    //         success: function (res) {
    //           console.log("###########")
    //           console.log(res.userInfo)
    //         }
    //       })
    //     }
    //   }
    // })
  },

  //商品详情
  getHfInfo: function (uqid, goods_id) {
    ajax("/api/index/good_show", {
      data: {
        uqid: uqid,
        id:goods_id,//商品id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'GET'
    }, res => {
      if (res.error == 0) {
        let data = res.data
        let html = res.data.goods_introduction
          .replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
          .replace(/<p>/ig, '<p style="font-size: 15px;width:100%; line-height: 25px;">')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img$1  style="width: 100%;"')
          .replace(/width="322" height="420"\//, "");
        console.log(html)
        console.log(res.data)

        data.goods_introduction=html
        console.log(data)

        this.setData({
          hfinfo: data
        })
      }

    })
  },

  //获取输入的手机号
  changePhone:function(e){
    var phone = e.detail.value;
    this.setData({
      phone: phone
    });
  },

  //立即获取智能康复计划  && 授权
  
  bindGetUserInfo(e){
    var that = this;
    console.log("--------------")
    console.log(e.detail.userInfo)

    if(this.data.islogin){
      this.getPhoneAdd()
    }
    else{
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        var code = wx.getStorageSync("code");

        ajax('/api/index/login', {
          data: {
            js_code: code,
            nickname: e.detail.userInfo.nickName,
            avatar: e.detail.userInfo.avatarUrl
          },
          header: {
            'Accept': 'application/json', // 默认值
          },
        }, res => {
        
          if (res.error == 0) {
            wx.setStorageSync("uqid", res.data.uqid)

            that.setData({
              uqid: res.data.uqid,
              session_key: res.data.session_key
            });
            this.isPhone();

          } else if (res.error == 4003) { //重复授权
            this.isPhone();
          }
        })
      } else {
        wx.showToast({
          title: '请先授权！',
          icon: 'none',
          duration: 2000
        })

      }
    }

    
  },
 
  //判断是否授权手机号
  isPhone: function () {
    var that = this;
    var tel = wx.getStorageSync("tel");
    console.log("------------------------"+tel)
    if (tel == undefined || tel == '') { //用户没有授权手机号
      that.setData({
        isPhoneAuth: true
      });
    } else { //用户已经授权手机号
      that.setData({
        isPhoneAuth: false
      });
      this.getTelAdd();
    }
  },

  //授权手机号
  getPhoneNumber(e) {
    this.setData({
      isPhoneAuth: false
    })
    console.log(this.data.session_key);
    
    if (e.detail.encryptedData) {
      ajax("/api/index/phone_decrypt", {
        data: {
          session: this.data.session_key,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
        method: 'POST'
      }, res => {
        // console.log(res);
        if (res.error == 0) {
          var tel = res.data.phoneNumber;
          wx.setStorageSync("tel", tel)
          this.getPhoneAdd();
          this.getTelAdd();
        }
      })
      
    }else{
      this.getPhoneAdd();
      
    }
  },
  //拒绝授权手机号
  refuseUserInfo:function(){
    this.setData({
      isPhoneAuth:false
    });
    this.getPhoneAdd();
  },
 

  //输入的手机号提交
  getPhoneAdd: function () {
    var that = this;
    console.log(this.data.uqid)
    console.log(this.data.phone)
    console.log(this.data.goods_id)

    ajax("/api/index/phone_add", {
      data: {
        uqid: this.data.uqid,
        phone: this.data.phone,
        goods_id: this.data.goods_id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method:'POST'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        wx.setStorageSync("pid", res.data.pid)
        wx.navigateTo({
          url: '/pages/functionalimpairment/functionalimpairment',
        })
      } else if (res.error == 1) { //已有进展
        wx.setStorageSync("pid", res.data.pid)
        wx.navigateTo({
          url: '/pages/functionalimpairment/functionalimpairment',
        })
      }
    })
  },

  //授权手机号提交
  getTelAdd:function(){
    var tel = wx.getStorageSync("tel");
    ajax("/api/index/phone_wx_sq_add", {
      data: {
        uqid: this.data.uqid,
        phone: tel,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        
      }
    })
  },

  //判断是否已经测评过
  isPatient: function (){
    ajax("/api/index/is_patient", {
      data: {
        uqid: this.data.uqid,
        goods_id: this.data.goods_id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      // console.log(res);
      if (res.error == 0) {//获取进展 pid
        if (res.data.status == 0) { //1-已有进展 0-没有
          wx.setStorageSync("pid", res.data.pid)
          this.setData({
            isplan: false
          });
        } else if (res.data.status == 1){
          wx.setStorageSync("pid", res.data.pid)
          this.setData({
            isplan: true
          });
        }
      }
    })
   
  },

  // //重新测评
  // againEvaluation:function(){
  //   wx.navigateTo({
  //     url: '/pages/functionalimpairment/functionalimpairment',
  //   })
  // },
  // //查看康复计划
  // viewPlan: function () {
  //   var pid = wx.getStorageSync("pid");
  //   ajax("/api/index/generation_plan", {
  //     data: {
  //       uqid: this.data.uqid,
  //       pid: pid,
  //     },
  //     header: {
  //       'Accept': 'application/json', // 默认值
  //     },
  //     method: 'GET'
  //   }, res => {
  //     if (res.error == 0) {
  //       wx.navigateTo({
  //         url: '/pages/myreserveplan/myreserveplan',
  //       })
  //     } else if (res.error == 1) {
  //       wx.showToast({
  //         title: '您生成的康复方案无效，请重新测评！',
  //         icon:'none',
  //         duration:2000
  //       })
  //     }
  //   })
    

  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                islogin: true
              });
            }
          })
        }
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})